﻿using DH.Core;
using DH.Core.Helper;
using DH.Core.MapperHelper;
using DH.Data;
using DH.Data.ORM.EF;
using DH.Data.ORM.EF.Extensions;
using DH.Entity;
using DH.Service.ViewModels;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DH.Service.Domain
{
  public  class FeaturesService: BaseService<FeaturesEntity, string>
    {
        protected IServiceCollection _serviceCollection;

        public FeaturesService(IServiceCollection service, DbCoreUnitOfWork unitOfWork) : base(service,unitOfWork)
        {
            this._serviceCollection = service;
        }

        public PagedData<FeaturesEntity> GetList(string key,string sortName,string sortOrder, FeaturesQueryDto filter, Pagination page)
        {
            var roleQuery = GetAllSync() as IQueryable<FeaturesEntity>;
            roleQuery = roleQuery.Where(c => c.Id != Guid.Empty.ToString());



            if (!string.IsNullOrWhiteSpace(filter.code))
            {
                roleQuery = roleQuery.Where(c => (c.Code.Contains(filter.code)));
            }
            if (!string.IsNullOrWhiteSpace(filter.type))
            {
                roleQuery = roleQuery.Where(c => (c.Type.Contains(filter.type)));
            }
            if (filter.isManage!=null)
            {
                roleQuery = roleQuery.Where(c => (c.IsManage==filter.isManage));
            }
            if (!string.IsNullOrWhiteSpace(filter.resourceTypeId))
            {
                roleQuery = roleQuery.Where(c => (c.ResourceTypeId == filter.resourceTypeId));
            }
            if (!string.IsNullOrWhiteSpace(sortName)&&sortName=="code")
            {

                if (sortOrder=="asc")
                {
                    return roleQuery.OrderBy(c=>c.Code).TakePageData(page);
                }
                else if (sortOrder == "desc")
                {
                    return roleQuery.OrderByDescending(c => c.Code).TakePageData(page);
                }

            }

            var tableEntityList = roleQuery.OrderBy(c => c.CreatedOn).TakePageData(page);
            return tableEntityList;
        }

        public FeaturesEntity Add(FeaturesViewModel viewModel)
        {
            FeaturesEntity model;
            model = DHMapper.Map<FeaturesViewModel, FeaturesEntity>(viewModel);
            model.CreatedOn = DateTimeOffset.Now;
            model.UpdatedOn = DateTimeOffset.Now;
            model.SortIndex = 0;

            InsertSync(model);

            return model;
        }

        public FeaturesEntity Edit(FeaturesViewModel viewModel)
        {
            var oldObj = GetSync(viewModel.Id);
            var entityObj = DHMapper.Map<FeaturesViewModel, FeaturesEntity>(viewModel, oldObj);

            entityObj.UpdatedOn = DateTimeOffset.Now;

            UpdateSync(entityObj);

            return entityObj;

        }

        public bool InsertFeatures(IEnumerable<FeaturesViewModel> viewModels)
        {
            var models = new List<FeaturesEntity>();
            foreach (var vm in viewModels)
            {
                FeaturesEntity model;
                model = DHMapper.Map<FeaturesViewModel, FeaturesEntity>(vm);
                model.CreatedOn = DateTimeOffset.Now;
                model.UpdatedOn = DateTimeOffset.Now;
                model.SortIndex = 0;
                models.Add(model);
            }

            _unitOfWork.ExecuteAndCommit(() => {
                _repository.Add(models);
            });


            return true;
        }

        public void Delete(string[] ids)
        {
            var models = GetByQuery(c => ids.Contains(c.Id));
            DeleteSync(models);
        }


        public List<FeaturesEntity> GetAllFeatures()
        {
            var res = GetAllSync();
            return res.ToList();
        }

        public List<FeaturesViewModel> GetFeatures(bool? status, bool? isManage, string resourceId, string featuresType)
        {
            var res = GetAllSync();
            if (status != null)
            {
                res = res.Where(c => c.Status == status);
            }
            if (isManage!=null) {
                res = res.Where(c => c.IsManage == isManage);
            }
            if (!string.IsNullOrWhiteSpace(resourceId))
            {
                res = res.Where(c=>c.ResourceTypeId==resourceId);
            }
            if (!string.IsNullOrWhiteSpace(featuresType))
            {
                res = res.Where(c => c.Type == ConstHelper.FeaturesFuncType);
            }

            return res.Select(c=> {
                return DHMapper.Map<FeaturesEntity, FeaturesViewModel>(c);
            }).ToList();
        }


        /// <summary>
        /// 获取资源功能集
        /// </summary>
        /// <returns></returns>
        public List<FeaturesButtonsDto> GetResourceFeatures(string resourceId)
        {
            var sql = string.Format(@"SELECT fuc.Id AS FeatrueId,
                                       fuc.Description AS FeatureName,
                                       sb.Name  AS ButtonName,
                                       sb.Icon  AS ButtonIcon
                                         FROM UiFeaturesButton  uibtn
                                         JOIN Sys_Button  sb
                                         ON uibtn.ButtonId = sb.Id
                                         JOIN Features fuc
                                         ON uibtn.FeatureId = fuc.Id
                                         AND fuc.Type = 'DH.Features.Function'
                                         AND fuc.ResourceTypeId = '{0}'
                                         WHERE sb.Status = 1
                                         AND fuc.Status = 1
                                         AND fuc.IsManage=1
                                ", resourceId);
            var res = _repository.Context.Database.SqlQuery<FeaturesButtonsDto>(sql);
            return res.ToList();

        }
    }
}
